package com.zhangxin.aiInterview.manager.work_flow.hr_interview_analyze;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zhangxin.aiInterview.manager.work_flow.hr_interview_analyze.model.HrInterviewAnalysisData;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class HrInterviewAnalyze {
    public static void main(String[] args) throws Exception {
        System.out.println(analyzeHrInterview(1916016714226561026L, 1959923658176638978L));
    }

    /**
     * 分析HR面试结果
     *
     * @param userId
     * @param hrInterviewId
     * @return
     * @throws Exception
     */
    public static HrInterviewAnalysisData analyzeHrInterview(Long userId, Long hrInterviewId) throws Exception {

        URL url = new URL("https://api.dify.ai/v1/workflows/run");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 必须设置的请求头
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer app-ALGxWJIQwm9xsXm67jsrizuc");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "text/event-stream");

        // 关键连接配置
        conn.setDoOutput(true);
        conn.setChunkedStreamingMode(0); // 启用分块传输
        conn.setReadTimeout(0); // 禁用读取超时

        // 发送请求体
        // todo 后期将数据库修改为线上数据库，因为这个操作是查询的线上数据库中的数据，线上数据库并没有本地数据库的这些数据
        String body = String.format(
                "{\"inputs\": {\"userId\": \"%s\", \"hrInterviewId\": \"%s\"}, \"response_mode\": \"streaming\", \"user\": \"abc-123\"}",
                userId, hrInterviewId);
        System.out.println("body: " + body);
        try (OutputStream os = conn.getOutputStream()) {
            os.write(body.getBytes(StandardCharsets.UTF_8));
        }

        // 处理流式响应
        String result = "";
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getInputStream()))) {

            String line;
            while ((line = reader.readLine()) != null) {
                if(line.isEmpty()) continue;
                System.out.println("line:" + line);
                // 只获取最后一部分的数据
                JSONObject jsonObject = extractOutputs(line);
                if (ObjUtil.isEmpty(jsonObject)) continue;
                assert jsonObject != null;
                result = jsonObject.toString();
                // 处理json数据
                return parse(result);
            }
        }
        return null;
    }

    /**
     * 提取 workflow_finished 事件中的 outputs 数据
     *
     * @param sseEvent 原始事件字符串（如 "data: {...}"）
     * @return 成功返回 JSONObject 格式的 outputs，失败返回 null
     */
    public static JSONObject extractOutputs(String sseEvent) {
        // 1. 校验并去除 "data: " 前缀
        if (!sseEvent.startsWith("data: ")) {
            return null;
        }
        String jsonStr = sseEvent.substring(6).trim();

        // 2. 解析为 JSONObject
        JSONObject event = JSONUtil.parseObj(jsonStr);
        if (event == null) {
            return null;
        }

        // 3. 校验事件类型
        if (!"workflow_finished".equals(event.getStr("event"))) {
            return null;
        }

        // 4. 提取 outputs
        JSONObject data = event.getJSONObject("data");
        if (data == null) {
            return null;
        }
        return data.getJSONObject("outputs");
    }

    /**
     * 处理json数据
     *
     * @param jsonStr
     * @return
     */
    public static HrInterviewAnalysisData parse(String jsonStr) {
        System.out.println("hr面试分析结果原始数据结构:   " + jsonStr);
        JSONObject json = JSONUtil.parseObj(jsonStr);

        // 解析 hr-out1：沟通表达分析
        JSONObject out1 = json.getJSONObject("hr-out1");
        HrInterviewAnalysisData.CommunicationAbilityAnalysis communication = new HrInterviewAnalysisData.CommunicationAbilityAnalysis();
        
        // 兼容新的数据结构，尝试从可能存在的字段中获取数据
        communication.setMicroExpression(out1.getStr("microExpression"));
        communication.setFacialActions(out1.getStr("facialActions"));
        communication.setSpeechRate(out1.getStr("speechRate"));
        communication.setAudioEmotion(out1.getStr("audioEmotion"));
        communication.setBodyMovements(out1.getStr("bodyMovements"));
        communication.setCommunicationSummary(out1.getStr("summary"));
        
        // 如果传统字段为空，尝试从眼动数据等新的字段中构建摘要
        if (communication.getCommunicationSummary() == null) {
            StringBuilder summaryBuilder = new StringBuilder();
            
            String eyeBlink = out1.getStr("eyeBlink");
            String mouthPuff = out1.getStr("mouthPuff");
            String eyeUpLeft = out1.getStr("eyeUpLeft");
            String eyeUpRight = out1.getStr("eyeUpRight");
            
            if (eyeBlink != null) {
                summaryBuilder.append("眨眼频率:").append(eyeBlink).append("; ");
            }
            if (mouthPuff != null) {
                summaryBuilder.append("嘴部动作:").append(mouthPuff).append("; ");
            }
            if (eyeUpLeft != null || eyeUpRight != null) {
                summaryBuilder.append("眼部动作:左").append(eyeUpLeft != null ? eyeUpLeft : "0")
                           .append("次,右").append(eyeUpRight != null ? eyeUpRight : "0").append("次");
            }
            
            String summary = summaryBuilder.toString();
            if (!summary.isEmpty()) {
                communication.setCommunicationSummary(summary);
            }
        }

        // 解析 hr-out2：多模态分析和每题分析
        JSONObject out2 = json.getJSONObject("hr-out2");
        JSONArray questionListJson = out2.getJSONArray("questionList");
        List<HrInterviewAnalysisData.QuestionEvaluation> questionList = new ArrayList<>();

        for (int i = 0; i < questionListJson.size(); i++) {
            JSONObject questionObj = questionListJson.getJSONObject(i);
            HrInterviewAnalysisData.QuestionEvaluation question = new HrInterviewAnalysisData.QuestionEvaluation();

            question.setQuestion(questionObj.getStr("question"));
            question.setAnswer(questionObj.getStr("answer"));
            question.setAnswerEvaluationSummary(questionObj.getStr("summary"));

            Object emoObjRaw = questionObj.get("multimodal_emotion");
            List<HrInterviewAnalysisData.MultimodalEmotionDetail> emotionDetails = new ArrayList<>();

            if (emoObjRaw instanceof JSONObject) {
                // 单个对象
                emotionDetails.add(parseEmotionDetail((JSONObject) emoObjRaw));
            } else if (emoObjRaw instanceof JSONArray) {
                // 多个对象
                JSONArray emoArray = (JSONArray) emoObjRaw;
                for (int j = 0; j < emoArray.size(); j++) {
                    emotionDetails.add(parseEmotionDetail(emoArray.getJSONObject(j)));
                }
            }

            question.setEmotionDetails(emotionDetails);
            questionList.add(question);
        }

        HrInterviewAnalysisData.MultimodalAnalysisResult multimodal = new HrInterviewAnalysisData.MultimodalAnalysisResult();
        multimodal.setQuestionList(questionList);
        multimodal.setOverallMultimodalSummary(out2.getStr("Summary"));

        // 提取每个问题的分数
        List<Double> scores = new ArrayList<>();
        for (int i = 0; i < questionListJson.size(); i++) {
            JSONObject questionObj = questionListJson.getJSONObject(i);
            if (questionObj.containsKey("score")) {
                scores.add(questionObj.getDouble("score"));
            }
        }

        // 封装最终对象
        HrInterviewAnalysisData result = new HrInterviewAnalysisData();
        result.setCommunicationAbility(communication);
        result.setMultimodalAnalysis(multimodal);
        result.setScores(scores);

        return result;
    }

    // 工具方法：解析 emotion 对象
    private static HrInterviewAnalysisData.MultimodalEmotionDetail parseEmotionDetail(JSONObject emoObj) {
        HrInterviewAnalysisData.MultimodalEmotionDetail detail = new HrInterviewAnalysisData.MultimodalEmotionDetail();

        detail.setMicroExpression(emoObj.getStr("microExpression"));
        detail.setAudioEmotion(emoObj.getStr("audioEmotion"));
        detail.setConsistency(emoObj.getStr("consistency"));

        Object facialActionsRaw = emoObj.get("facialActions");
        if (facialActionsRaw instanceof JSONObject) {
            detail.setFacialActions(facialActionsRaw.toString());
        } else if (facialActionsRaw instanceof String) {
            detail.setFacialActions((String) facialActionsRaw);
        } else {
            detail.setFacialActions(null);
        }

        Object bodyMovementsRaw = emoObj.get("bodyMovements");
        if (bodyMovementsRaw instanceof JSONObject) {
            detail.setBodyMovements(bodyMovementsRaw.toString());
        } else if (bodyMovementsRaw instanceof String) {
            detail.setBodyMovements((String) bodyMovementsRaw);
        } else {
            detail.setBodyMovements(null);
        }

        return detail;
    }

}
